﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace SynoManager.DownloadStation.Search
{
    /// <summary>
    /// Base class for Search Results that are created through <seealso cref="HttpSearchEngineBase" /> implementations.
    /// </summary>
    /// <remarks>
    /// Search Results are parsed using the regular expression in <see cref="HttpSearchEngineBase.Regex" />.
    /// <para>Each result is then parsed as a <see cref="Match" /> which is passed to the <see cref="HttpSearchResultBase(HttpSearchEngineBase, Match)">constructor</see>.</para>
    /// <para>The <see cref="Match"/> is stored internally (private field) and properties are returned as they are needed.</para>
    /// </remarks>
    public abstract class HttpSearchResultBase : SearchResultBase
    {
        private readonly Match match;

        /// <summary>
        /// Create a new instance of the <see cref="HttpSearchResultBase" />.
        /// </summary>
        /// <param name="engine">Engine for which the result is created</param>
        /// <param name="match">Match on which this result should be based</param>
        protected HttpSearchResultBase(HttpSearchEngineBase engine, Match match) : base(engine)
        {
            this.match = match;
        }

        /// <summary>Gets the title of the task.</summary>
        public override string Title
        {
            get { return HttpUtility.HtmlDecode(match.Groups["Title"].Value); }
        }

        /// <summary>Gets the download url.</summary>
        public override string DownloadUrl
        {
            get { return match.Groups["DownloadUrl"].Value; }
        }

        /// <summary>Gets the url for more information.</summary>
        public override string MoreInfoUrl
        {
            get { return match.Groups["MoreInfoUrl"].Value; }
        }

        /// <summary>Gets the number of available seeders.</summary>
        public override int Seeders
        {
            get { return int.Parse(match.Groups["Seeders"].Value); }
        }

        /// <summary>Gets the number of available leechers.</summary>
        public override int Leechers
        {
            get { return int.Parse(match.Groups["Leechers"].Value); }
        }

        /// <summary>Gets the filesize of the result.</summary>
        public override long Size
        {
            get
            {
                string value = HttpUtility.HtmlDecode(match.Groups["Size"].Value);
                value = value.Replace((char)0xA0, (char)0x20);
                return ByteSize.Parse(value);
            }
        }

        /// <summary>Gets the category for the result.</summary>
        public override string Category
        {
            get { return HttpUtility.HtmlDecode(match.Groups["Category"].Value); }
        }
    }
}
